package com.fz.study.project.utils;


import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.UUID;
import lombok.AllArgsConstructor;
import lombok.RequiredArgsConstructor;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;

import java.util.Collections;
import java.util.concurrent.TimeUnit;

/*
* 获取释放锁
*
* */
@AllArgsConstructor
@RequiredArgsConstructor
public class SimpleRedisLock implements ILock{
    private final StringRedisTemplate stringRedisTemplate;

//    业务名称，也就是锁的名称
    private String name;

    private static final String KEY_PREFIX = "lock:";
    private static final String ID_PREFIX = UUID.randomUUID().toString(true)+"-";

//    提前读取lua脚本文件
    private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
//        设置脚本位置
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
//        配置其返回值类型
        UNLOCK_SCRIPT.setResultType(Long.class);
    }
    @Override
    public boolean tryLock(long timeoutSec) {
//        获取线程id
        String threadId =ID_PREFIX + Thread.currentThread().getId();
//        获取锁
        Boolean success = stringRedisTemplate.opsForValue().setIfAbsent(KEY_PREFIX + name, threadId, timeoutSec, TimeUnit.SECONDS);
        /*
        * Boolean.TRUE.equals(success):
        * 如果success结果是true就返回true
        * 如果success结果是false就返回false
        * 如果success为空就返回false
        * 这样可以避免空指针的问题
        * */
        return Boolean.TRUE.equals(success);
    }

    @Override
    public void unlock() {
//       调用lua脚本
        stringRedisTemplate.execute(UNLOCK_SCRIPT,
                Collections.singletonList(KEY_PREFIX + name),
                ID_PREFIX + Thread.currentThread().getId());
    }


//    @Override
//    public void unlock() {
//        /*
//        * 对标识做一个再次验证，主要作用是释放锁的时候防止误删的情况
//        * */
//        String threadId =ID_PREFIX + Thread.currentThread().getId();
//        String id = stringRedisTemplate.opsForValue().get(KEY_PREFIX + name);
////        判断二者标识是否一致
//        if (threadId.equals(id)){
//            //     一致   释放锁
//            stringRedisTemplate.delete(KEY_PREFIX +name);
//        }
//    }
}
